//1.prefs相关
function setPrefs(key, value) {
    api.setPrefs({key: key, value: value});
}
function getPrefs(key) {
    return api.getPrefs({key: key, sync: true});
}
function removePrefs(key) {
    api.removePrefs({key: key});
}
function hasPrefs(key) {
    return !!api.getPrefs({key: key, sync: true});
}
//2.加载进度条
var hasProgress = false;
var loadingLabel;
var loadingId;
function showProgress() {
    if (!hasProgress) {
        hasProgress = true;
        setTimeout(_showProgress, 500);
    }
}
function _showProgress() {
    if (hasProgress) {
        api.showProgress({
            title: '',
            text: '',
            modal: false
        });
    }
}
function hideProgress() {
    if (hasProgress) {
        api.hideProgress();
        hasProgress = false;
    }
}
// function showProgress() {
//     if(!loadingLabel) {
//         loadingLabel = api.require('loadingLabel');
//     }
//
//     if (!hasProgress) {
//         hasProgress = true;
//         // setTimeout(_showProgress, 500);
//         _showProgress();
//     }
// }
// function _showProgress() {
//     if (hasProgress) {
//         loadingLabel.open({
//             centerY:300,
//             w:60,
//             h:60,
//             gifPath:'widget://image/gif/1.gif'
//         }, function (ret) {
//             loadingId = ret.id;
//         })
//     }
// }
// function hideProgress() {
//     if (hasProgress) {
//         loadingLabel.close({
//             id:loadingId
//         });
//         hasProgress = false;
//     }
// }
//3.处理安卓端appParam的古怪格式!
function appParamToJson(param) {
    switch (typeof param) {
        case 'object':
            return param;
        case 'string':
            var json = {};
            param = param.replace('{', '').replace('}', '');
            var arr = param.split(',');
            for (var i = 0; i < arr.length; i++) {
                var arr2 = arr[i].split('=');
                json[arr2[0]] = arr2[1];
            }
            return json;
        default:
            alert('未知的appParam格式:' + typeof(param));
            return false;
    }
}
//4.安卓按两次back退出应用
function doubleBack() {
    if (api.systemType != 'android') {
        return;
    } else {
        var flag = false;

        function _setTimeout() {
            flag = false;
        }

        api.addEventListener({
            name: 'keyback'
        }, function () {
            if (!flag) {
                api.toast({
                    msg: '再按一次返回键退出',
                    duration: 2000
                });
                flag = true;
                setTimeout(_setTimeout, 2000);
            } else {
                api.closeWidget({
                    silent: true
                });
            }
        });
    }
}
//5.level_id相关
/*var memberStyles = [
 {
 level_id: '1',
 level_name: '试用会员/顾客',
 usercard_bg: 'usercard_bg_id1.png',
 usercard_change: 'usercard_id1.png',
 level_bg: 'level_bg_id1.png',
 levelup_bg: null,
 color: '#905e04',
 changeColor: '#905e04',
 bgcolor1: '#fbd777',
 bgcolor2: '#fff0a8',
 }, {
 level_id: '2',
 level_name: '白银会员/会员',
 usercard_bg: 'usercard_bg_id2.png',
 usercard_change: 'usercard_id2.png',
 level_bg: 'level_bg_id2.png',
 levelup_bg: 'levelup_bg_id2.png',
 color: '#252525',
 changeColor: '#252525',
 bgcolor1: '#a9a7a7',
 bgcolor2: '#ded8d3',
 }, {
 level_id: '3',
 level_name: '钻石会员/店长',
 usercard_bg: 'usercard_bg_id5.png',
 usercard_change: 'usercard_id5.png',
 level_bg: 'level_bg_id5.png',
 levelup_bg: 'levelup_bg_id5.png',
 color: '#03fdff',
 changeColor: '#03fdff',
 bgcolor1: '#011343',
 bgcolor2: '#0226a5',
 }, {
 level_id: '4',
 level_name: '铂金会员/主管',
 usercard_bg: 'usercard_bg_id4.png',
 usercard_change: 'usercard_id6.png',
 level_bg: 'level_bg_id4.png',
 levelup_bg: 'levelup_bg_id4.png',
 color: '#1c1c18',
 changeColor: '#fff',
 bgcolor1: '#4c4c50',
 bgcolor2: '#b2b3c5',
 }, {
 level_id: '5',
 level_name: '黄金会员/经理',
 usercard_bg: 'usercard_bg_id3.png',
 usercard_change: 'usercard_id3.png',
 level_bg: 'level_bg_id3.png',
 levelup_bg: 'levelup_bg_id3.png',
 color: '#9e4706',
 changeColor: '#9e4706',
 bgcolor1: '#967212',
 bgcolor2: '#dfcc7c',
 }, {
 level_id: '22',
 level_name: '白银会员/会员',
 usercard_bg: 'usercard_bg_id2.png',
 usercard_change: 'usercard_id2.png',
 level_bg: 'level_bg_id2.png',
 levelup_bg: 'levelup_bg_id2.png',
 color: '#252525',
 changeColor: '#252525',
 bgcolor1: '#a9a7a7',
 bgcolor2: '#ded8d3',
 }, {
 level_id: '23',
 level_name: '钻石会员/店长',
 usercard_bg: 'usercard_bg_id5.png',
 usercard_change: 'usercard_id5.png',
 level_bg: 'level_bg_id5.png',
 levelup_bg: 'levelup_bg_id5.png',
 color: '#03fdff',
 changeColor: '#03fdff',
 bgcolor1: '#011343',
 bgcolor2: '#0226a5',
 }, {
 level_id: '24',
 level_name: '铂金会员/主管',
 usercard_bg: 'usercard_bg_id4.png',
 usercard_change: 'usercard_id6.png',
 level_bg: 'level_bg_id4.png',
 levelup_bg: 'levelup_bg_id4.png',
 color: '#1c1c18',
 changeColor: '#fff',
 bgcolor1: '#4c4c50',
 bgcolor2: '#b2b3c5',
 }, {
 level_id: '25',
 level_name: '黄金会员/经理',
 usercard_bg: 'usercard_bg_id3.png',
 usercard_change: 'usercard_id3.png',
 level_bg: 'level_bg_id3.png',
 levelup_bg: 'levelup_bg_id3.png',
 color: '#9e4706',
 changeColor: '#9e4706',
 bgcolor1: '#967212',
 bgcolor2: '#dfcc7c',
 }
 ];*/
var memberStyles = [
    {
        level_id: '1',
        level_name: '试用会员/顾客',
        usercard_bg: 'usercard_bg_id1.png',
        usercard_change: 'usercard_id1.png',
        level_bg: 'level_bg_id1.png',
        levelup_bg: null,
        color: '#905e04',
        bgcolor1: '#fbd777',
        bgcolor2: '#fff0a8',
    },
    {
        level_id: '2',
        level_name: '白银会员/会员',
        usercard_bg: 'usercard_bg_id2.png',
        usercard_change: 'usercard_id2.png',
        level_bg: 'level_bg_id2.png',
        levelup_bg: 'levelup_bg_id2.png',
        color: '#252525',
        bgcolor1: '#a9a7a7',
        bgcolor2: '#ded8d3',
    },
    {
        level_id: '3',
        level_name: '黄金会员/主管',
        usercard_bg: 'usercard_bg_id3.png',
        usercard_change: 'usercard_id3.png',
        level_bg: 'level_bg_id3.png',
        levelup_bg: 'levelup_bg_id3.png',
        color: '#9e4706',
        bgcolor1: '#967212',
        bgcolor2: '#dfcc7c',
    },
    {
        level_id: '4',
        level_name: '铂金会员/经理',
        usercard_bg: 'usercard_bg_id4.png',
        usercard_change: 'usercard_id4.png',
        level_bg: 'level_bg_id4.png',
        levelup_bg: 'levelup_bg_id4.png',
        color: '#1c1c18',
        bgcolor1: '#4c4c50',
        bgcolor2: '#b2b3c5',
    },
    {
        level_id: '9',
        level_name: '钻石会员/总监',
        usercard_bg: 'usercard_bg_id5.png',
        usercard_change: 'usercard_id5.png',
        level_bg: 'level_bg_id5.png',
        levelup_bg: 'levelup_bg_id5.png',
        color: '#03fdff',
        bgcolor1: '#011343',
        bgcolor2: '#0226a5',
    },
    {
        level_id: '6',
        level_name: '黑卡会员',
        usercard_bg: 'usercard_bg_id6.png',
        usercard_change: 'usercard_id6.png',
        level_bg: 'level_bg_id6.png',
        levelup_bg: 'levelup_bg_id6.png',
        color: '#ffffff',
        bgcolor1: '#010101',
        bgcolor2: '#383437',
    },
    {
        level_id: '7',
        level_name: '代理会员',
        usercard_bg: 'usercard_bg_id7.png',
        usercard_change: 'usercard_id7.png',
        level_bg: 'level_bg_id7.png',
        levelup_bg: null,
        color: '#25466d',
        bgcolor1: '#5596b6',
        bgcolor2: '#c1dee1',
    },
    {
        level_id: '8',
        level_name: '品牌会员',
        usercard_bg: 'usercard_bg_id8.png',
        usercard_change: 'usercard_id8.png',
        level_bg: 'level_bg_id8.png',
        levelup_bg: null,
        color: '#2b665d',
        bgcolor1: '#54a9a1',
        bgcolor2: '#a4d2c9',
    },
    {
        level_id: '22',
        level_name: '白银会员/会员',
        usercard_bg: 'usercard_bg_id2.png',
        usercard_change: 'usercard_id2.png',
        level_bg: 'level_bg_id2.png',
        levelup_bg: 'levelup_bg_id2.png',
        color: '#252525',
        bgcolor1: '#a9a7a7',
        bgcolor2: '#ded8d3',
    },
    {
        level_id: '23',
        level_name: '黄金会员/主管',
        usercard_bg: 'usercard_bg_id3.png',
        usercard_change: 'usercard_id3.png',
        level_bg: 'level_bg_id3.png',
        levelup_bg: 'levelup_bg_id3.png',
        color: '#9e4706',
        bgcolor1: '#967212',
        bgcolor2: '#dfcc7c',
    },
    {
        level_id: '24',
        level_name: '铂金会员/经理',
        usercard_bg: 'usercard_bg_id4.png',
        usercard_change: 'usercard_id4.png',
        level_bg: 'level_bg_id4.png',
        levelup_bg: 'levelup_bg_id4.png',
        color: '#1c1c18',
        bgcolor1: '#4c4c50',
        bgcolor2: '#b2b3c5',
    },
    {
        level_id: '25',
        level_name: '钻石会员/总监',
        usercard_bg: 'usercard_bg_id5.png',
        usercard_change: 'usercard_id5.png',
        level_bg: 'level_bg_id5.png',
        levelup_bg: 'levelup_bg_id5.png',
        color: '#03fdff',
        bgcolor1: '#011343',
        bgcolor2: '#0226a5',
    },
    {
        level_id: '27',
        level_name: '白银会员/会员',
        usercard_bg: 'usercard_bg_id2.png',
        usercard_change: 'usercard_id2.png',
        level_bg: 'level_bg_id2.png',
        levelup_bg: 'levelup_bg_id2.png',
        color: '#252525',
        bgcolor1: '#a9a7a7',
        bgcolor2: '#ded8d3',
    },
    {
        level_id: '28',
        level_name: '黄金会员/主管',
        usercard_bg: 'usercard_bg_id3.png',
        usercard_change: 'usercard_id3.png',
        level_bg: 'level_bg_id3.png',
        levelup_bg: 'levelup_bg_id3.png',
        color: '#9e4706',
        bgcolor1: '#967212',
        bgcolor2: '#dfcc7c',
    },
    {
        level_id: '29',
        level_name: '铂金会员/经理',
        usercard_bg: 'usercard_bg_id4.png',
        usercard_change: 'usercard_id4.png',
        level_bg: 'level_bg_id4.png',
        levelup_bg: 'levelup_bg_id4.png',
        color: '#1c1c18',
        bgcolor1: '#4c4c50',
        bgcolor2: '#b2b3c5',
    },
    {
        level_id: '30',
        level_name: '钻石会员/总监',
        usercard_bg: 'usercard_bg_id5.png',
        usercard_change: 'usercard_id5.png',
        level_bg: 'level_bg_id5.png',
        levelup_bg: 'levelup_bg_id5.png',
        color: '#03fdff',
        bgcolor1: '#011343',
        bgcolor2: '#0226a5',
    },
];
function getMemberStyle(level_id) {
    for (var i = 0, l = memberStyles.length; i < l; i++) {
        if (memberStyles[i].level_id == level_id) {
            return memberStyles[i];
        }
    }
    return memberStyles[1];
}
//6.设置下拉刷新
function setRefreshHeaderInfo(callback) {
    api.setRefreshHeaderInfo({
        bgColor: '#f7f7f7',
        textColor: '#000',
        textDown: '下拉刷新...',
        textUp: '松开刷新...',
        showTime: true
    }, callback);
}

function setUserRefreshHeaderInfo(callback) {
    api.setRefreshHeaderInfo({
        bgColor: '#82C8F0',
        textColor: '#000',
        textDown: '下拉刷新...',
        textUp: '松开刷新...',
        showTime: true
    }, callback);
}
//7.监听updUser事件
function listenUpdUser(user) {
    api.addEventListener({
        name: 'updUser'
    }, function (ret) {
        if (ret && ret.value) {
            for (var i in ret.value) {
                user[i] = ret.value[i];
            }
            setPrefs('user', user);
        } else {
            var data = {
                member_id: getPrefs('member_id')
            };
            var callback = function (ret) {
                user = ret.content;
                setPrefs('user', user);
                api.sendEvent({
                    name: 'getUnReadMsgCount',
                    extra: {count: user.unReadMessageCount}
                });
            };
            pinet.post(URL.getUserinfo, data, callback);
        }
    });
}

//jump方法
function actionJump(action) {
    var jump = action.jump,
        action_id = action.action_id,
        actionParams = action.action_params;
    if (!(jump && actionParams)) {
        return;
    }
    if (action_id == 4) {
        var category_id = actionParams.category_id;
        var index = -1;
        var js1 = "vm.changeStatus(" + index + "," + category_id + ")";
        api.execScript({
            name: 'index',
            frameName: 'mall_left',
            script: js1
        });
        var js2 = "switchActiveCls(1)";
        api.execScript({
            name: 'index',
            script: js2
        });
        if (api.winName != 'index') {
            openWin('index');
        }
        api.setFrameGroupIndex({
            name: 'group',
            index: 1,
        });
    } else {
        var url = 'widget:/' + jump;
        api.openWin({
            name: 'jump',
            url: url,
            pageParam: actionParams
        });
    }
}

//header后退按钮指令
Vue.directive('backFrame', {
    bind: function (el) {
        el.onclick = function () {
            api.closeFrame();
        }
    }
});
//时间过滤器/
function Time(timestamp) {
    var _time = new Date(parseInt(timestamp) * 1000);
    this.year = _time.getFullYear();
    this.month = _time.getMonth() + 1;
    this.date = _time.getDate();
    this.hours = _time.getHours();
    this.minutes = _time.getMinutes();
    this.seconds = _time.getSeconds();
    for (var i in this) {
        if (this[i] < 10) {
            this[i] = '0' + this[i];
        }
    }
}
//年月日 2017-07-29
Vue.filter('date2', function (value) {
    if (isNaN(value)) {
        return value;
    }
    var time = new Time(value);
    return time.year + '-' + time.month + '-' + time.date;
});
//年月日 2017/07/29
Vue.filter('date', function (value) {
    var time = new Time(value);
    return time.year + '/' + time.month + '/' + time.date;
});
//年月日 时分秒 2017/07/29 22:19:18
Vue.filter('time', function (value) {
    var time = new Time(value);
    return time.year + '/' + time.month + '/' + time.date + ' ' + time.hours + ':' + time.minutes + ':' + time.seconds;
});
Vue.filter('number', function (value) {
    return parseInt(value / 86400000);
});
Vue.filter('double', function (value) {
    return Number(value).toFixed(2);
});
Vue.filter('maxByte_12', function (value) {
    var byte = 0;
    var arr = value.toString().split('');

    var newValue = '';
    var reg = /[^\x00-\xff]/;
    for (var i = 0, l = arr.length; i < l; i++) {
        byte += reg.test(arr[i]) ? 2 : 1;
        if (byte > 12) {
            return newValue;
        } else {
            newValue += arr[i];
        }
    }
    return value;
});
//扫描
Vue.directive('openScanner', {
    bind: function (el) {
        el.onclick = function () {
            var scanner = api.require('FNScanner');
            scanner.openScanner({}, function (ret) {
                if (ret.content) {
                    var url = ret.content;
                    api.openWin({
                        name: "share",
                        url: "html/mall/share.html",
                        pageParam: {
                            url: url,
                        }
                    })
                }
            });
        }
    }
});
//通知某页面刷新
function reload(winName) {
    api.execScript({
        name: winName,
        script: 'window.location.reload();'
    });
}
function reloadFrame(winName, frameName) {
    api.execScript({
        name: winName,
        frameName: frameName,
        script: 'window.location.reload();'
    });
}

//添加v-row-active指令
Vue.directive('rowActive', function (el, binding) {
    el.ontouchstart = function () {
        el.classList.add('row-active');
    };
    el.ontouchmove = function () {
        el.classList.remove('row-active');
    };
    el.ontouchend = function () {
        el.classList.remove('row-active');
    };
    if (binding.modifiers.tapmode) {
        if (api.systemType == 'ios') {
            el.setAttribute('tapmode', '');
        }
    }
});

//按设备屏幕分辨率宽使用图片
function setBSImg() {
    var winWidth = api.winWidth;
    Vue.BSImg = winWidth > 375 ? 'big' : 'small';
}
Vue.directive('src', {
    inserted: function (el, binding) {
        var _src = binding.value;
        var arr = _src.split('/');
        arr[arr.length - 2] += '/' + Vue.BSImg;
        el.src = arr.join('/');
    }
});
Vue.directive('active', function (el, binding) {
    var _src = binding.value;
    var arr = _src.split('/');
    arr[arr.length - 2] += '/' + Vue.BSImg;
    var src = arr.join('/');
    el.style.backgroundImage = 'url(' + src + ')';
});
//添加Vue方法：禁止触屏滑动事件
Vue.prototype.preventTouchmove = function (flag) {
    document.ontouchmove = function (e) {
        if (flag) {
            e.preventDefault();
        }
    }
};

//加载页面自动聚焦指令
Vue.directive('focus', {
    inserted: function (el) {
        el.focus();
    }
});

//打开新窗口指令
Vue.directive('openWin', function (el, binding) {
    if (binding.modifiers.tapmode) {
        if (api.systemType == 'ios') {
            el.setAttribute('tapmode', '');
        }
    }
    var _url = el.getAttribute('vurl');
    var params = binding.value ? binding.value : '';
    var fn = openWin;
    el.onclick = function () {
        fn(_url, params);
    }
});
function openWin(_url, params, otherAttr) {
    var arr = _url.split('/');
    var name = arr[arr.length - 1];
    var url = _url + '.html';

    var winAttr = {
        name: name,
        url: url,
        pageParam: params,
        scrollToTop: true
    };
    if (name == 'index' || name == 'user2') {
        winAttr['slidBackEnabled'] = false;
        if (params && params.startImg) {
            winAttr['animation'] = {type: 'none', duration: 0};
        }
    } else if (name == 'changeUser') {
        winAttr['reload'] = true;
    }

    if (otherAttr) {
        concatJson(winAttr, otherAttr);
    }

    api.openWin(winAttr);
}
function closeWin(name) {
    api.closeWin({
        name: name
    });
}

//重新登录
function reLogin() {
    removePrefs('token');
    removePrefs('user');
    openWin('widget://html/login/login', {from: api.winName});
}

//将json2的属性添加到json1中
function concatJson(json1, json2) {
    for (var i in json2) {
        json1[i] = json2[i];
    }
}

//友盟统计
var tdPage = {
    home: '首页',
    mall: '商城',
    collection: '收藏',
    user: '我的',
    aboutUs: '关于我们',
    accounts: '提现账户管理',
    activate: '激活职位',
    addmember: '新增会员',
    authorize: '第三方授权',
    bindAlipay: '绑定支付宝',
    bindCard: '绑定银行卡',
    changeUser: '切换会员',
    deposit: '我的保证金',
    feedback: '问题反馈',
    help: '帮助',
    level_up: '会员升级',
    member_level: '我的会员等级',
    message: '消息',
    modifyPwd: '提现密码设置',
    myearnings: '我的收益',
    mypromotion: '我的推广',
    mypromotion2: '特殊会员-我的推广',
    payment: '支付信息',
    prefer: '偏好',
    remark: '备注',
    settings: '设置',
    shareQrcode: '分享二维码',
    superior: '我的推荐人',
    sys_settings: '系统设置',
    updpwd: '修改密码',
    user2: '特殊会员-我的',
    userinfo: '个人资料',
    username: '会员昵称',
    withdraw: '提现',
    withdraw_detail: '提现详情',
    withdraw_list: '提现明细',
    gross_income: '收益类型',
    income_detail: '收益详情',
    spread_consume: '自推广消费明细',
    total_income: '总收益明细',
    search: '搜索页面',
    search_list: '分类页面',
    search_result: '搜索结果',
    share: 'share',
    my_order: '我的订单',
    order_detail: '订单详情',
    shopactivity:'活动专区',
    seckill:'商品抢购',
    share:'推荐商品',
    addcategory:'添加分类',
    addgoods:'添加商品',
    categorydetail:'分类商品详情',
    categoryinfo:'分类详情',
    editcategory:'修改分类',
    goodsetting:'商品管理',
    introduction:'店铺介绍',
    myshop:'我的店铺管理',
    search:'搜索查询阿里妈妈商品',
    setshop:'修改店铺信息',
    shopinfo:'店铺详情',
    shoplibrary:'商品库',
    shopname:'店铺名称修改',
    shopuser:'店主信息',
    updatecategory:'修改分类详细信息',
    addshop:'购买会员或店铺',
    changeMember:'切换用户',
    submember:'我的团队',
    submember:'我的子店铺',
    share_info:'分享详情',
    seckill_goodsinfo:'抢购商品信息',
    goods_info:'活动分类商品详细信息',
    makeprofit:'购买会员或店铺选择',

};

var talkingData;
function onPageStart(pageName, callback) {
   pageName = pageName || tdPage[api.winName];
   if (!talkingData) {
       talkingData = api.require('talkingData');
   }
   talkingData.onPageStart({pageName: pageName,});
}

function onPageEnd(pageName) {
   pageName = pageName || tdPage[api.winName];
   if (talkingData) {
       var ret = talkingData.onPageEnd({pageName: pageName});
   }
}

function onEvent(eventId,eventLabel,attributes) {
    if (!talkingData) {
        talkingData = api.require('talkingData');
    }
    talkingData.onEvent({
        eventId: eventId,
        eventLabel:eventLabel,
        parameters: attributes,
    });
    var data = {
      event_id: eventId,
      event_label:eventLabel,
      parameters: attributes,
    };
    var callback = function (ret) {
    };
    pinet.post(URL.sendEvent, data, callback);
    /*
    eventId：
    类型：字符串
    默认值：无
    描述：自定义事件的ID，不能为空
    eventLabel：
    类型：字符串
    默认值：无
    描述：自定义事件的标签，可以为空
    parameters：
    类型：JOSN对象
    默认值：无
    描述：自定义事件的参数，可以为空
     */
}
//header后退按钮指令
Vue.directive('back', function (el, binding) {
    if (binding.modifiers.tapmode) {
        if (api.systemType == 'ios') {
            el.setAttribute('tapmode', '');
        }
    }
    el.classList.add(Vue.BSImg);
    el.onclick = function () {
        if (api.systemType == 'android') {
            onPageEnd();
        }
        api.closeWin();
    }

});
//转发
function openMNActionButton(share,suffix) {
    var path = 'widget://image/' + Vue.BSImg + '/';
    MNActionButton.open({
        title: '分享',
        content: "分享商品给好友，好友购买成功后\n您将可获得一定的分享奖励",
        layout: {
            row: 1,
            col: 3,
            // rowSpacing: 0,
            // colSpacing: 50,
            // offset: 0
        },
        animation: true,
        autoHide: true,
        styles: {
            maskBg: 'rgba(0,0,0,0.2)',
            bg: '#fff',
            cancelButton: {
                size: 0,
                bg: '#fff',
                icon: 'widget://res/action-button-cancel.png'
            },
            item: {
                titleColor: '#888',
                titleHighlight: 'dd2727',
                titleSize: 12
            },
            indicator: {
                color: '#c4c4c4',
                highlight: '#9e9e9e'
            }
        },
        items: [{
            icon: path + 'share_btn_moments.png',
            title: '朋友圈'
        }, {
            icon: path + 'share_btn_wechat.png',
            title: '微信好友'
        }, {
            icon: path + 'share_btn_qq.png',
            title: 'QQ好友'
        }],
    }, function (ret) {
        if (ret.eventType == 'click') {
            switch (ret.index) {
                case 0:
                suffix.attributes.share_id=0;
                onEvent(suffix.eventId,suffix.eventLable,suffix.attributes);
                    share_wx('timeline', share);
                    break;
                case 1:
                suffix.attributes.share_id=1;
                onEvent(suffix.eventId,suffix.eventLable,suffix.attributes);
                    share_wx('session', share);
                    break;
                case 2:
                suffix.attributes.share_id=2;
                onEvent(suffix.eventId,suffix.eventLable,suffix.attributes);
                    share_qq(share);
                    break;
            }
        }
    })
}
function openMNActionInviteButton(share,suffix) {
    var path = 'widget://image/' + Vue.BSImg + '/';
    MNActionButton.open({
        title: '分享',
        content: "邀请您的好友一起来友人店轻松创业",
        layout: {
            row: 1,
            col: 3,
            // rowSpacing: 0,
            // colSpacing: 50,
            // offset: 0
        },
        animation: true,
        autoHide: true,
        styles: {
            maskBg: 'rgba(0,0,0,0.2)',
            bg: '#fff',
            cancelButton: {
                size: 0,
                bg: '#fff',
                icon: 'widget://res/action-button-cancel.png'
            },
            item: {
                titleColor: '#888',
                titleHighlight: 'dd2727',
                titleSize: 12
            },
            indicator: {
                color: '#c4c4c4',
                highlight: '#9e9e9e'
            }
        },
        items: [{
            icon: path + 'share_btn_moments.png',
            title: '朋友圈'
        }, {
            icon: path + 'share_btn_wechat.png',
            title: '微信好友'
        }, {
            icon: path + 'share_btn_qq.png',
            title: 'QQ好友'
        }],
    }, function (ret) {
        if (ret.eventType == 'click') {
            switch (ret.index) {
              case 0:
              suffix.attributes.share_id=0;
              onEvent(suffix.eventId,suffix.eventLable,suffix.attributes);
                  share_wx('timeline', share);
                  break;
              case 1:
              suffix.attributes.share_id=1;
              onEvent(suffix.eventId,suffix.eventLable,suffix.attributes);
                  share_wx('session', share);
                  break;
              case 2:
              suffix.attributes.share_id=2;
              onEvent(suffix.eventId,suffix.eventLable,suffix.attributes);
                  share_qq(share);
                  break;
            }
        }
    })
}
function openMNActionButtonShop(share) {
  var path = 'widget://image/' + Vue.BSImg + '/';
  MNActionButton.open({
      title: '分享',
      content: "分享商品给好友，好友购买成功后\n您将可获得一定的分享奖励",
      layout: {
          row: 1,
          col: 3,
          // rowSpacing: 0,
          // colSpacing: 50,
          // offset: 0
      },
      animation: true,
      autoHide: true,
      styles: {
          maskBg: 'rgba(0,0,0,0.2)',
          bg: '#fff',
          cancelButton: {
              size: 0,
              bg: '#fff',
              icon: 'widget://res/action-button-cancel.png'
          },
          item: {
              titleColor: '#888',
              titleHighlight: 'dd2727',
              titleSize: 12
          },
          indicator: {
              color: '#c4c4c4',
              highlight: '#9e9e9e'
          }
      },
      items: [{
          icon: path + 'share_btn_moments.png',
          title: '朋友圈'
      }, {
          icon: path + 'share_btn_wechat.png',
          title: '微信好友'
      }, {
          icon: path + 'share_btn_qq.png',
          title: 'QQ好友'
      }],
  }, function (ret) {
      if (ret.eventType == 'click') {
          switch (ret.index) {
              case 0:
                  share_wx('timeline', share);
                  break;
              case 1:
                  share_wx('session', share);
                  break;
              case 2:
                  share_qq(share);
                  break;
          }
      }
  })
}
function share_wx(scene, share) {
    var shareWebpageParam = {
        scene: scene,
        title: share.title,
        description: share.content,
        contentUrl: share.url
    };
    api.imageCache({
        url: share.image,
    }, function (ret) {
        if (ret && ret.status) {
            shareWebpageParam['thumb'] = ret.url;
        }
        wx.shareWebpage(shareWebpageParam, function () {
        });
        MNActionButton.close();
    });
}

function share_qq(share) {
    var qq = api.require('QQPlus');
    var json = {
        url: share.url,
        title: share.title,
        description: share.content,
        type: 'QFriend'
    };
    api.imageCache({
        url: share.image
    }, function (ret) {
        if (ret && ret.status) {
            json['imgUrl'] = ret.url;
        }
        ;
        qq.shareNews(json, function () {
        });
        MNActionButton.close();
    });
}
// for "image-resize"
function getStyle(el, name) {
    if (window.getComputedStyle) {
        return window.getComputedStyle(el, null)[name];
    } else {
        return el.currentStyle[name];
    }
}
// for "image-resize"
function getWH(el) {
    var val = el.offsetWidth,
        which = ['Left', 'Right'];
    // display is none
    if (val === 0) {
        return [0, 0];
    }

    for (var i = 0, a; a = which[i++];) {
        val -= parseFloat(getStyle(el, "border" + a + "Width")) || 0;
        val -= parseFloat(getStyle(el, "padding" + a)) || 0;
    }
    var width = val;


    var val = el.offsetHeight,
        which = ['Top', 'Bottom'];

    // display is none
    if (val === 0) {
        return [0, 0];
    }

    for (var i = 0, a; a = which[i++];) {
        val -= parseFloat(getStyle(el, "border" + a + "Width")) || 0;
        val -= parseFloat(getStyle(el, "padding" + a)) || 0;
    }

    var height = val;

    return [width, height];
}

//图片预加载指令
Vue.directive("image-resize", {
    inserted: function (el, binding) {
        var default_src = "";
        el.src = default_src;
        //默认或获取宽度、高度、比值
        if (binding.value.width || binding.value.ratio || binding.value.height) {
            var width = binding.value.width ? binding.value.width : "100%";
            var ratio = binding.value.ratio ? binding.value.ratio : 1;
            var height = binding.value.height ? binding.value.height : "0";
            var is_parent = binding.value.isParent;

            var parentWH = getWH(el.parentNode);

            var clientWidth = is_parent ? parentWH[0] : document.documentElement.clientWidth;
            var clientHeight = is_parent ? parentWH[1] : document.documentElement.clientHeight;
            //设定图片宽度
            if (width.indexOf("%") > 0) {
                width = width.replace("%", "") / 100;
                width = clientWidth * width;
            } else if (width.indexOf("px")) {
                width = width.replace("px", "") * 1;
            }
            //设定图片高度
            if (height == 0) {
                height = width * ratio;
            } else if (height.indexOf("%") > 0) {
                height = height.replace("%", "") / 100;
                height = clientHeight * height;
            } else if (height.indexOf("px")) {
                height = height.replace("px", "") * 1;
            }

            el.style.width = width + "px";
            el.style.height = height + "px";
            el.width = width;
            el.height = height;
        }
        var img_url = binding.value.src ? binding.value.src : "";
        if (img_url) {
            var im = new Image();
            im.onload = function () {
                el.src = img_url;
            };
            im.src = img_url;
        }
    }
});

//为了使api.parseTapmode()有效的v-myclick指令
Vue.directive('myclick', function (el, binding) {
    var fn;
    var args;

    switch (typeof(binding.value)) {
        case 'function':
            fn = binding.value;
            el.onclick = function (e) {
                if (binding.modifiers.stop) {
                    e.stopPropagation();
                    if (el == e.target) {
                        fn();
                    }
                } else {
                    fn();
                }
            };
            break;
        case 'object':
            var value = binding.value;
            args = value[0];

            switch (typeof value[1]) {
                case 'function':
                    fn = value[1];
                    if (args instanceof Array) {
                        el.onclick = function (e) {
                            if (binding.modifiers.stop) {
                                e.stopPropagation();
                                if (el == e.target) {
                                    fn.apply(this, args);
                                }
                            } else {
                                fn.apply(this, args);
                            }
                        };
                    } else {
                        el.onclick = function (e) {
                            if (binding.modifiers.stop) {
                                e.stopPropagation();
                                if (el == e.target) {
                                    fn(args);
                                }
                            } else {
                                fn(args);
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
            break;
    }
    if (api.systemType == 'ios') {
        el.setAttribute('tapmode', '');
    }
});

Vue.directive('inputClick', function (el) {
    el.setAttribute('tapmode', '');
    el.onclick = function () {
        el.focus();
    }
});

function setTapmode(el) {
    if (api.systemType != 'ios') {
        return;
    }
    if (el instanceof Array) {
        for (var i = 0, l = el.length; i < l; i++) {
            // setTapmode(el[i]);
            el[i].setAttribute('tapmode', '');
        }
    } else {
        el.setAttribute('tapmode', '');
    }
}

function changeFavor(good) {
    if(!getPrefs('token')){
        reLogin();
    }else{
        showProgress();
        var data = {
            member_id: getPrefs('member_id'),
            goods_id: good.goods_id
        };
        var callback = function (ret) {
            if (ret.message == '1') {
                api.toast({
                    msg: '收藏成功',
                    duration: 2000,
                    location: 'bottom'
                });
                onEvent('商品收藏点击');
                good.favor = '1';
            } else {
                api.toast({
                    msg: '取消收藏',
                    duration: 2000,
                    location: 'bottom'
                });
                good.favor = '0';
            }
            api.sendEvent({
                name: 'collection'
            });
        };
        pinet.post(URL.changeFavor, data, callback);
    }
}

function openGoodsDetail(goods_id) {
    if (getPrefs('token')) {
        onEvent('推荐商品点击','', {goods_id: goods_id},'');
        openWin('widget://html/home/browser', {goods_id: goods_id});
    }else{
        reLogin();
    }
}
function openGoodsInfo(goods_id) {
  onEvent('商品详情点击','', {goods_id: goods_id},'');
  openWin('widget://html/home/goods_info', {goods_id: goods_id});
}
//各个模块
function showMeiQia() {
    mq.setTitleColor({
        color: "#f0f0f0"
    });
    mq.setTitleBarColor({
        color: "#9d0152"
    });
    mq.setLoginCustomizedId({
        id: user.customer_id,
    });
    var gender;
    if (user.sex != '0') {
        gender = user.sex == '1' ? '男' : '女';
    } else {
        gender = '未知';
    }
    mq.setClientInfo({
        name: user.nickname,
        avatar: user.portrait,
        tel: user.phone,
        gender: gender,
        address: user.province + user.city + user.district,
    });
    mq.show();
}

 function seckillRemind(time, good, type) {
     if(!getPrefs('token')){
         reLogin();
     }else{
         showProgress();
         var data = {
             member_id: getPrefs('member_id'),
             time: time,
             goods_id:good.goods_id,
             type:type
         };
         var callback = function (ret) {
             if (ret.message == '1') {
                 api.toast({
                     msg: '设置提醒成功',
                     duration: 2000,
                     location: 'bottom'
                 });
                 good.remind = '1';
             }else{
               api.toast({
                   msg: '取消提醒成功',
                   duration: 2000,
                   location: 'bottom'
               });
               good.remind = '0';
             }
             api.sendEvent({
                 name: 'remind'
             });
         };
         pinet.post(URL.changeRemind, data, callback);
     }
 }

 Array.prototype.indexOf = function (val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) return i;
    }
    return -1;
};

Array.prototype.remove = function (val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};

function sendPhoneInfo(){
  var phoneinfo = {};
  var phoneinfomore = {};
  var device = function (res) {
    if(res){
      phoneinfomore = res;
      phoneinfo.device_type = api.systemType;
      phoneinfo.os_version = api.systemVersion;
      phoneinfo.idfa = api.systemType;
      phoneinfo.imei = phoneinfomore.imei;
      phoneinfo.imsi = phoneinfomore.imsi;
      phoneinfo.mac = phoneinfomore.ipMac;
      phoneinfo.network = api.connectionType;
      phoneinfo.ip = phoneinfomore.ip;
      phoneinfo.brand = phoneinfomore.brand;
      phoneinfo.model = api.deviceModel;
      phoneinfo.width = api.screenWidth;
      phoneinfo.height = api.screenHeight;
      phoneinfo.tpid = getPrefs('tpid');
      phoneinfo.cid = getPrefs('cid');
      var  data={
        phoneinfo :phoneinfo
      }
      var callback = function (ret) {
        var infos = ret.content;
        var uid = infos.uid;
        if(uid){
          setPrefs('uid', uid);
        }
      };
      pinet.post(URL.sendPhoneInfo, data, callback);
    }
  };
  phoneInfoMoreModule = api.require('phoneInfoMore');
  var res = phoneInfoMoreModule.getBaseInfo(device);
}

function setchannelinfo(){
  var _datas = api.readFile({sync: true, path: 'widget://res/channel.json'});
  var datas = JSON.parse(_datas);
  setPrefs('tpid', datas.cid);
  setPrefs('cid', datas.tpid);
}
